﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Nox.Amuse.Helpers
{
    static class FileHelper
    {
        /// <summary>
        /// Creates a new TextWriter for writing out a file
        /// </summary>
        /// <param name="fileName">The name of the file that needs writing</param>
        /// <returns>An opened text writer</returns>
        public static TextWriter StartWritingTextFile(string fileName)
        {
            if (!Directory.Exists(GetApplicationDataFolderPath()))
                Directory.CreateDirectory(GetApplicationDataFolderPath());
            return new StreamWriter(GetApplicationDataFolderPath() + fileName);
        }

        public static TextWriter StartWritingTextFileToFullPath(string path)
        {
            if (!Directory.Exists(Path.GetDirectoryName(path)))
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            return new StreamWriter(path);
        }


        /// <summary>
        /// Creates a new TextReader for reading in a file
        /// </summary>
        /// <param name="fileName">The name of the file that needs reading</param>
        /// <returns>An opened text reader or null if the file could not be opened</returns>
        public static TextReader StartReadingTextFile(string fileName)
        {
            try
            {
                return new StreamReader(GetApplicationDataFolderPath() + fileName);
            }
            catch
            {
                return null;
            }
        }

        public static TextReader StartReadingTextFileFromFullPath(string path)
        {
            try
            {
                return new StreamReader(path);
            }
            catch
            {
                return null;
            }
        }

#if DEBUG
        // The folder name for Amuse's folder in AppData/Local
        const string FolderName = "AmuseDebug";
#else
        // The folder name for Amuse's folder in AppData/Local
        const string FolderName = "Amuse";
#endif   

        /// <summary>
        /// Returns the path to the application's data folder in the AppData / Local store
        /// </summary>
        /// <returns>The path with the trailing slash</returns>
        public static string GetApplicationDataFolderPath()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
                + Path.DirectorySeparatorChar
                + FolderName
                + Path.DirectorySeparatorChar;
        }

        public static void Delete(string fileName)
        {
            File.Delete(GetApplicationDataFolderPath() + fileName);
        }
    }
}
